import axios from 'axios';

import { showGlobalLoading, hideGlobalLoading } from '@/actions/loading';

import store from '@/store/configureStore';
const envConfig = require('@/config/env.config');

// 全局加载状态loading
const handleGlobalLoading = (namespace, type) => {
  if (!namespace) return;
  store.dispatch(
    type === 'show'
      ? showGlobalLoading({
          namespace,
        })
      : hideGlobalLoading({
          namespace,
        })
  );
};

const axiosInstance = axios.create({
  timeout: 60000,
});

axiosInstance.interceptors.response.use(
  (res) => {
    // 默认情况下 res.headers.authorization 的值是undefined，headers中没有authorization
    let token = res.headers.authorization; // 注意 axios获取到的response里面headers值 key都是小写，实际后端返回的key值规则是首字母大写
    if (token) {
      localStorage.setItem('Authorization', token);
      // setCookie('Authorization', token)
    }

    return res;
  },
  // error
  () => {}
);

export default function request({
  url,
  apiUrl,
  namespace,
  method = 'get',
  data,
  headers = {},
  successFun,
  errorFun,
  expectionFun,
}: any) {
  handleGlobalLoading(namespace, 'show');

  const token = localStorage.getItem('Authorization');

  //存在用户登录信息
  if (token) {
    headers.Authorization = token;
    headers['Accept-language'] = 'zh-CN'; //  语言配置
  }

  axiosInstance({
    method,
    url: `${apiUrl ? apiUrl : envConfig.API}${url}`,
    data,
    headers,
  })
    .then((res) => {
      handleGlobalLoading(namespace, 'hide');

      // 错误
      if (res.data.status === false) {
        // todo
        errorFun && errorFun(res.data);
        return;
      }

      successFun && successFun(res.data);
    })
    .catch((error) => {
      handleGlobalLoading(namespace, 'hide');

      expectionFun && expectionFun(error);
    });
}
